import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  DateDiff,
  DateStamp,
  FormatnumberZero,
  Mover,
  NumberDivide,
  getNowFormatDate,
} from '@/function.js';
// 视图插件
import { Button, Card, Col, DatePicker, Form, Input, Row, Select } from 'antd';
// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Fundanalysis from './Fundanalysis.js';
import Loading from '../../components/Loading/Loading';
import StandardTablePro from '@/components/UpgradeStandardTable/StandardTablePro';

// css OR less预编译器
// import styles from './All.less';
const SelectOption = Select.Option;

// 图片

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ third }) => ({
  third,
}))
@Form.create()
class ThirdWorth extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    charts: {},
    dates: [],
    netDates: [],
    date1: '',
    value: '',
    motify: '',
    date2: '',
    refresh: false,
    dataSource: {
      data: [],
      total: [],
      code: 0,
    },
  };

  onSelectDate1(e) {
    this.setState({
      date1: getNowFormatDate(e._d),
    });
  }

  valueChange(e) {
    this.setState({
      value: e.target.value,
    });
  }

  addIt() {
    const { dispatch } = this.props;
    const that = this;
    this.setState({
      refresh: true,
    });
    dispatch({
      type: 'third/AddValue',
      payload: { netDate: this.state.date1, netValue: Number(this.state.value) },
      callback: () => {
        this.dataSourceChange();
      },
    });
  }

  onSelectDate2(value) {
    this.setState({
      date2: value,
    });
  }

  onSelectDate3(value) {
    this.dataSourceChange(value)
  }

  // alterIt(){
  //   this.dataSourceChange();
  // }
  delIt() {
    const { dispatch } = this.props;
    const that = this;
    this.setState({
      refresh: true,
    });
    dispatch({
      type: 'third/DelValue',
      payload: { netDate: this.state.date2 },
      callback: () => {
        this.dataSourceChange();
      },
    });
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const { charts } = this.state;
    const { dates, netDates, refresh, dataSource } = this.state;
    const selectList = [];
    const selectListNet = [];
    if (dates) {
      for (let i = 0; i < dates.length; i++) {
        const item = dates[i];
        selectList.push(
          <SelectOption value={item.split(' ')[0]}>{item.split(' ')[0]}</SelectOption>
        );
      }
    }    if (netDates) {
      for (let i = 0; i < netDates.length; i++) {
        const item = netDates[i];
        selectListNet.push(
          <SelectOption value={item.split(' ')[0]}>{item.split(' ')[0]}</SelectOption>
        );
      }
    }
    return (
      <PageHeaderWrapper>
        <Card>
          <Col span={24} style={{ marginBottom: 15 }}>
            选择日期：{' '}
            <DatePicker
              // showTime
              placeholder="请选择"
              format="YYYY-MM-DD"
              style={{ width: 200, marginRight: 25 }}
              onChange={this.onSelectDate1.bind(this)}
            />
            净值：
            <Input style={{ width: 200, margin: 4 }} onChange={this.valueChange.bind(this)} />
            <Button onClick={this.addIt.bind(this)} style={{ marginLeft: 25 }} type="primary">
              添加
            </Button>
          </Col>
          <Col span={24}>
            选择日期：{' '}
            <Select
              style={{ width: 200 }}
              onSelect={this.onSelectDate2.bind(this)}
              placeholder="请选择日期"
            >
              {selectList}
            </Select>
            {/* 修改值： <Input style={{width: 200, margin:4, }} onChange={this.modifyChange.bind(this)}/> */}
            {/* <Button onClick={this.alterIt.bind(this)} style={{ marginLeft:25}} type="primary">修改</Button> */}
            <Button onClick={this.delIt.bind(this)} style={{ marginLeft: 25 }} type="primary">
              删除
            </Button>
          </Col>
          <Col span={24}  style={{marginTop:20}}>
            选择表格日期：{' '}
            <Select
              style={{ width: 200 }}
              onSelect={this.onSelectDate3.bind(this)}
              placeholder="请选择日期"
            >
              {selectListNet}
            </Select>
          </Col>
          <Col span={24} style={{marginBottom:20,marginTop:20}}>
          <StandardTablePro dataSource={dataSource} handleSave={this.handleSave.bind(this)}/>
          </Col>
          <Col span={24}>
          {charts.list ? (
            <div
              style={{
                textAlign: 'center',
                marginLeft: '-1%',
                fontWeight: '600',
                fontSize: '1rem',
              }}
            >
              {charts.name}&nbsp;&nbsp;{charts.list[charts.list.length - 1].date}
              {/* 涨幅：{(((charts.list[charts.list.length-1].fundNetValue-charts.list[charts.list.length-2].fundNetValue)/charts.list[charts.list.length-2].fundNetValue)*100).toFixed(2)+'%'} */}
              {/*  &nbsp;&nbsp;spy涨幅：{(((charts.list[charts.list.length-1].spyNetValue-charts.list[charts.list.length-2].spyNetValue)/charts.list[charts.list.length-2].spyNetValue)*100).toFixed(2)+'%' */}
              }
            </div>
          ) : null}
          <br />
          <br />
          {refresh ? <Loading /> : <Fundanalysis charts={charts} />}
          </Col>
        </Card>
      </PageHeaderWrapper>
    );
  }

  dataSourceChange(date) {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'third/GetDates',
      callback: res => {
        that.setState({ dates: res.list });
      },
    });
    dispatch({
      type: 'third/GetNetReportDates',
      callback: res => {
        that.setState({ netDates: res.list },()=>{
          // bank (string, optional): 新三号基金 银行 1：瑞银 2：花旗 3：中银 ,
          //   buyLv (number, optional): 新买入LV ,
          //   buyPrice (number, optional): 新买入成本 ,
          //   dailyFundIncome (number, optional): 每日收益 ,
          //   dailyInterest (number, optional): 每日付出利息 ,
          //   dataDate (string, optional): 日期 ,
          //   dividend (number, optional): 派息 ,
          //   fundIncome (number, optional): 累计收益 ,
          //   fundNet (number, optional): 基金净值 ,
          //   id (integer, optional): id ,
          //   interestRate (number, optional): 利率 ,
          //   itemType (string, optional): 类别 （分别为债券） ,
          // loanAmount (number, optional): 借款金额 ,
          //   marketValue (number, optional): 市值 ,
          //   mvChgValue (number, optional): 市值增长 ,
          //   principal (number, optional): 本金 ,
          //   sellLv (number, optional): 新卖出LV ,
          //   sellMv (number, optional): 新卖出市值 ,
          //   sellPrice (number, optional): 新卖出成本
          dispatch({
            type: 'third/GetNetReportDatas',
            payload:{netDate:date?date:that.state.netDates[0].split(' ')[0]},
            callback: res => {
              const dataSource = {
                title: `${date?date:that.state.netDates[0].split(' ')[0]} 三号基金日报`,
                // titleTotal: false,
                code: 1,
                data: res.list,
                total: [],
                columns: [
                  {
                    title: '类别',
                    type: 'string',
                    dataIndex: 'itemType',
                    width: 75,
                  },
                  {
                    title: '银行',
                    dataIndex: 'bank',
                    type: 'number',
                    width: 60,
                    filters: [
                      {
                        text: '瑞银',
                        value: 1,
                      },
                      {
                        text: '中银',
                        value: 2,
                      },
                      {
                        text: '花旗',
                        value: 3,
                      },
                    ],
                    render: (value, row, index) => {
                      if (value === 1) {
                        return '瑞银';
                      }
                      if (value === 2) {
                        return '中银';
                      }
                      if (value === 3) {
                        return '花旗';
                      }
                      return value;
                    },
                  },
                  {
                    title: '市值',
                    dataIndex: 'marketValue',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '累计收益',
                    dataIndex: 'fundIncome',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '基金净值',
                    dataIndex: 'fundNet',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '新买入成本',
                    dataIndex: 'buyPrice',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '新买入LV',
                    dataIndex: 'buyLv',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '新卖出成本',
                    dataIndex: 'sellPrice',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '新卖出LV',
                    dataIndex: 'sellLv',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '新卖出市值',
                    dataIndex: 'sellMv',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '市值增长',
                    dataIndex: 'mvChgValue',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '本金',
                    dataIndex: 'principal',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '借款金额',
                    dataIndex: 'loanAmount',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '利率',
                    dataIndex: 'interestRate',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '派息',
                    dataIndex: 'dividend',
                    width: 75,
                    type: 'number',
                    editable:true,
                  },
                  {
                    title: '每日付出利息',
                    dataIndex: 'dailyInterest',
                    width: 75,
                    type: 'number',
                  },
                  {
                    title: '每日收益',
                    dataIndex: 'dailyFundIncome',
                    width: 75,
                    type: 'number',
                  },
                ],
              };
              that.setState({ dataSource });
            },
          });
        });
      },
    });
    dispatch({
      type: 'third/GetCurve',
      callback: res => {
        that.setState({ charts: res, refresh: false });
      },
    });

  }

  getItemsArr(o)
  {
    let tmpArr = [];
    for(let item in o)
    {
      tmpArr.push(item);
    }
    return tmpArr;
  }

  handleSave(row, values) {
    const that = this;
    const { dispatch } = that.props;
    let property = this.getItemsArr(values)[0];
    let payload = {
      "buyLv": row.buyLv,
        "buyPrice": row.buyPrice,
        "dividend": row.dividend,
        "id": row.id,
        "marketValue": row.marketValue,
        "sellLv": row.sellLv,
        "sellMv": row.sellMv,
        "sellPrice": row.sellPrice,
      };
    payload[property] = typeof values[property] === 'string'? Number(values[property]):row[property];
    dispatch({
      type: 'third/GetNetReportDataReset',
      payload,
      callback: res => {
        that.dataSourceChange();
      },
    });
  }

  componentDidMount() {
    this.dataSourceChange();
  }

  componentWillUnmount() {}
}

export default ThirdWorth;
